<template>
  <div class="md-select-icon-base">
    <el-popover ref="mdSelectIconPopover" placement="bottom" :width="popoverWidth" trigger="click" popper-class="md-select-icon-popover">
      <div class="md-select-icon-data">
        <el-button v-for="(icon, index) in iconData" :key="index" :type="icon===val?'primary':'default'" @click="handleClick(icon)">
          <span>
            <md-icon :name="icon" size="19px" />
          </span>
        </el-button>
      </div>
      <el-input v-model="val" ref="mdSelectIconInput" readonly :placeholder="placeholder" slot="reference" clearable>
        <template slot="prepend" v-if="val">
          <md-icon :name="val" />
        </template>
      </el-input>
    </el-popover>
  </div>
</template>

<script>
import iconRes from './svg.icon.json'
export default {
  name: 'MdSelectIconBaseComponent',
  props: {
    value: [String],
    placeholder: {
      type: String,
      default: '请选择'
    },
  },
  watch: {
    value: {
      handler (val) {
        this.val = val
      },
      deep: true,
      immediate: true
    }
  },
  data () {
    return {
      val: null,
      popoverWidth: 0,
      iconData: []
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.popoverWidth = this.$refs.mdSelectIconInput.$el.offsetWidth

      this.iconData = iconRes.data
    })
  },
  methods: {
    handleClick (icon) {
      this.$emit('input', icon)
      this.$emit('change', icon)
      this.$refs.mdSelectIconPopover.doClose()
    }
  }
}
</script>

<style lang="less" scoped>
.md-select-icon-base {
  ::v-deep .el-popover__reference-wrapper {
    .el-input {
      .el-input-group__prepend {
        padding: 0px 8px !important;
      }
    }
  }
}
</style>